package com.heima.controller;

import com.heima.pojo.Result;
import com.heima.pojo.User;
import com.heima.service.UserService;
import com.heima.utils.JwtUtil;
import com.heima.utils.Md5Util;
import com.heima.utils.ThreadLocalUtil;
import org.codehaus.jettison.json.JSONObject;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
//@CrossOrigin
public class UserController {
/*
本类完成网页 `注册` 和 `登录` 数据的 `录入` 与 `查询` 与 `验证` 与 `分发令牌`
下一步：
    创建工具类：完成密码的加密
    创建工具类：创建令牌 和完成 令牌的校验
 */
    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //注册
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$")String password){
       /*
       //参数校验
        if(username != null && username.length()>=5 && username.length() <= 16 &&
        password != null && password.length() >= 5 && password.length() <= 16){

        }else {
            return Result.error("参数不合法");
        }
        */

        //查询用户
        User u = userService.findByUserName(username);
        if(u == null){
            //没有占用
            userService.register(username, password);
            return Result.success();
            // 注册
        }else {
            //占用
            return Result.error("用户名已被占用");
        }
    }

    //localhost:8080/user/login
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$")String password){
        //根据用户查询User
        User loginUser = userService.findByUserName(username);
        //判断是否查询到
        if(loginUser == null){
            return Result.error("用户名错误");
        }
        //判断密码是否正确
        if(Md5Util.string2MD5(password).equals(loginUser.getPassword())){
            //登录成功 返回令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            String token = JwtUtil.getToken(claims);
            //把token存储到redis中
            stringRedisTemplate.opsForValue().set(token,token,7, TimeUnit.DAYS);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    //获取用户详细信息
    //localhost:8080/user/userInfo
    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization")String token*/){
        //从token中获取用户名
        //根据用户名查询用户
       /* Map<String, Object> map = JwtUtil.parseToken(token);
        String username = (String) map.get("username");*/


        Map<String, Object> map = ThreadLocalUtil.get();
        System.out.println(map);
        String username = (String)map.get("username");

        User user = userService.findByUserName(username);
        return Result.success(user);
    }
    //更新用户信息
    //localhost:8080/user/update
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){
        userService.update(user);
        return Result.success();
    }

    //localhost:8080/user/updateAvatar
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    //localhost:8080/user/updatePwd
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params,@RequestHeader("Authorization") String token){

        System.out.println("params== " + params);
        System.out.println("token == " + token);

        //1.校验参数
        String oldPwd = params.get("oldPassword");
        String newPwd = params.get("newPassword");
        String rePwd = params.get("rePassword");

        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要的参数");
        }
        //原密码是否正确
        //调用userService根据用户名拿到原密码，再和old_pwd比对
        Map<String, Object> map = ThreadLocalUtil.get();
        String username= (String) map.get("username");
        User loginUser = userService.findByUserName(username);
        if(!Md5Util.string2MD5(oldPwd).equals(loginUser.getPassword())){
            return Result.error("原密码填写不正确");
        }
        //newPwd和rePwd是否一样
        if(!newPwd.equals(rePwd)){
            return Result.error("两次填写的新密码不一样");
        }
        //调用service完成密码更新
        userService.updatePwd(newPwd);

        //删除redis中对应的token
        stringRedisTemplate.opsForValue().getOperations().delete(token);
        return Result.success();
    }
}
